import { useEffect, useRef } from "react";
import { Parser, Player } from "svga";
import { PlayerConfigOptions } from "svga/dist/types";

export default function useSvga(
  svgaPath: string,
  config?: PlayerConfigOptions
) {
  const player = useRef<Player>();
  const parser = useRef<Parser>(
    new Parser({
      isDisableImageBitmapShim: true,
    })
  );

  async function initSvga(container: HTMLCanvasElement) {
    const svga = await parser.current.load(svgaPath);
    player.current = new Player({
      container,
      isCacheFrames: true,
      isUseIntersectionObserver: false,
      isOpenNoExecutionDelay: false,
      ...config,
    });

    player.current.onEnd = () => console.log("hello");
    player.current

    return await player.current.mount(svga);
  }

  useEffect(() => {
    return () => {
      player.current?.destroy();
      parser.current.destroy();
    };
  }, []);

  return {
    init: initSvga,
    player,
  };
}
